﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace wUniAppPCL.MVVM
{
  public enum FilterTypeEnum { FilterA, FilterB, FilterC};

  public class FilterHelper<T> : wObservableObject where T : IPerson
  {
    public FilterHelper()
    {
      // default
      PostFixArray = new string[] { "ová", "icová", "ská" };
    }

    public static string[] PostFixArray { get; set;  }

    protected virtual void OnFilterChanged()
    {
      var handler = FilterChanged;
      if (handler != null)
      {
        handler(this, EventArgs.Empty);
      }
    }
    public event EventHandler FilterChanged;

    public IList Items
    {
      get { return Enum.GetValues(typeof(FilterTypeEnum)); }
    }

    FilterTypeEnum filterType = FilterTypeEnum.FilterA;
    public FilterTypeEnum SelectedFilter
    {
      get { return filterType; }
      set { if (SetProperty(ref filterType, value, "SelectedFilter")) OnFilterChanged(); }
    }

    public void ApplyFilter(string text, IList<T> srcItems, ref IList<T> dstItems)
    {
      IEnumerable<T> res = null;
      dstItems.Clear();

      switch (SelectedFilter)
      {
        case FilterTypeEnum.FilterA: res = GetFilteredByA(srcItems, text);
          break;
        case FilterTypeEnum.FilterB: res = GetFilteredByB(srcItems, text);
          break;
        case FilterTypeEnum.FilterC: res = GetFilteredByC(srcItems, text);
          break;
      }

      foreach (T item in res)
      {
        dstItems.Add(item);
      }
    }

    // Priezviska su rovnake
    public IEnumerable<T> GetFilteredByA(IList<T> sourceList, string text)
    {
      return sourceList.Where(c => c.LastName.ToLower().StartsWith(text.Trim().ToLower()));
    }
    // priezviska rovnake az na pripony v postFixArray
    public IEnumerable<T> GetFilteredByB(IList<T> sourceList, string text)
    {
      return sourceList.Where(c =>
      {
        return c.LastName.ToLower().StartsWith(text.Trim().ToLower()) && !c.LastName.ContainPostFixes(PostFixArray);
      });
    }
    // rovnake az na jedno pismeno (preklep)
    public IEnumerable<T> GetFilteredByC(IList<T> sourceList, string text, int count = 1)
    {
      return sourceList.Where(c => c.LastName.ToLower().DamerauLevenshteinDistanceTo(text.Trim().ToLower()) <= count);
    }
  }

  internal static class StringEx
  {
    public static bool ContainPostFixes(this String str, string[] postFixArray)
    {
      foreach (string pf in postFixArray)
      {
        if (str.EndsWith(pf))
        {
          return true;
        }
      }
      return false;
    }



  }
}
